package com.jxwifi.cloud.quickclean.pay;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.idroid.async.AsyncWorker;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.bean.PayParamsBean;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.simple.eventbus.EventBus;

import java.util.Map;

/**
 * Created by bichuanfeng on 2016/12/26.
 */

public class PayUtil {

    private static PayUtil instance;

    private PayUtil() {
    }

    public static PayUtil getInstance() {
        if (instance == null) {
            instance = new PayUtil();
        }
        return instance;
    }

    public void aliPay(final Context context, final PayParamsBean params) {
        AsyncWorker.execute(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) context);
                Map<String, String> result = alipay.payV2(params.getAliPayResult(), true);
                AliPayResult payResult = new AliPayResult((Map<String, String>) result);
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    EventBus.getDefault().post(new PayResult(true, params.getOutTradNo()), "e-PayResult");
                } else if (TextUtils.equals(resultStatus, "6001") || TextUtils.equals(resultStatus, "6002")) {
                    Toaster.show(context, payResult.getMemo());
                    EventBus.getDefault().post(new PayResult(false, "需要登录"));
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    Toaster.show(context, "支付失败 " + payResult.getMemo());
                    EventBus.getDefault().post(new PayResult(false, "支付失败 " + payResult.getMemo()));
                }
            }
        });
    }


    public void WXPay(final Context context,WxpayParams wxpayParams){
        IWXAPI api = WXAPIFactory.createWXAPI(context, StateUtils.WX_APPID);
        api.registerApp(wxpayParams.getAppId());
        PayReq req = new PayReq();
        req.timeStamp = wxpayParams.getTimeStamp();
        req.packageValue = wxpayParams.getPackageX();
        req.partnerId=wxpayParams.getPartnerid();//后台返回数据：mchId == partnerId
        req.prepayId=wxpayParams.getPrepayid();
        req.sign = wxpayParams.getPaySign();
        req.appId = wxpayParams.getAppId();
        req.signType = wxpayParams.getSignType();
        req.nonceStr = wxpayParams.getNonceStr();
        req.extData = "";
        api.sendReq(req);
    }

}
